package org.oslo.mule.aggregator;

import java.util.Iterator;

import org.mule.impl.MuleMessage;
import org.mule.routing.AggregationException;
import org.mule.routing.inbound.AbstractEventAggregator;
import org.mule.routing.inbound.EventGroup;
import org.mule.umo.UMOEvent;
import org.mule.umo.UMOMessage;
import org.oslo.domain.LocationInfo;
import org.oslo.domain.SearchResult;
import org.oslo.sessioninfo.domain.SessionsTO;

public class ConferenceAggregator extends AbstractEventAggregator {	
	
	protected Object getEventGroupIdForEvent(UMOEvent event) {
		UMOMessage message = event.getMessage();
		if(message.getPayload() instanceof LocationInfo) {
			LocationInfo locationInfo = (LocationInfo) message.getPayload();
			return locationInfo.getSearchIdentifier();
		} else {
			SessionsTO sessionsTO = (SessionsTO) message.getPayload();
			return sessionsTO.getSearchIdentifier();
		}
	}

	protected boolean shouldAggregateEvents(EventGroup eventGroup) {
		Iterator itEvent = eventGroup.iterator();
		boolean isLocationPresent = false;
		boolean isSessionInfoPresent = false;
		while(itEvent.hasNext()) {
			UMOEvent event = (UMOEvent) itEvent.next();
			if(event.getMessage().getPayload() instanceof LocationInfo) {
				isLocationPresent = true;
			} else {
				isSessionInfoPresent = true;
			}
		}
		return isLocationPresent && isSessionInfoPresent;
	}
	
	protected UMOMessage aggregateEvents(EventGroup eventGroup) throws AggregationException {
		Iterator itEvent = eventGroup.iterator();
		SearchResult result = new SearchResult();
		while(itEvent.hasNext()) {
			UMOEvent event = (UMOEvent) itEvent.next();
			if(event.getMessage().getPayload() instanceof LocationInfo) {
				result.setLocationInfo((LocationInfo) event.getMessage().getPayload());
			} else {
				result.setSessionsTO((SessionsTO) event.getMessage().getPayload());
			}
		}
		return new MuleMessage(result);
	}


}
